interface Env {
  WORKER_API_KEY: string;
  CLOUDFLARE_API_TOKEN: string;
  CLOUDFLARE_ACCOUNT_ID: string;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext) {
    if (request.method !== 'POST') {
      return new Response('Expected POST', { status: 405 });
    }

    // 1. 认证客户端 (使用 X-Api-Key 请求头)
    const clientApiKey = request.headers.get('X-Api-Key');
    // 'WORKER_API_KEY' 是你在 Cloudflare Secrets 中设置的变量名
    if (!clientApiKey || clientApiKey !== env.WORKER_API_KEY) {
      return new Response('Unauthorized: Missing or invalid API Key', { status: 401 });
    }

    try {
      // 2. 解析客户端请求体 (只需要 prompt)
      const clientData = await request.json() as { prompt?: string, steps?: unknown };
      const prompt = clientData.prompt;
      const steps = clientData.steps;

      if (!prompt) {
        return new Response('Missing "prompt" in request body', { status: 400 });
      }

      // 3. 从环境变量(Secrets)获取 Worker 自身的凭证
      const apiToken = env.CLOUDFLARE_API_TOKEN;
      const accountId = env.CLOUDFLARE_ACCOUNT_ID;

      if (!apiToken || !accountId) {
          console.error('ERROR: Missing Cloudflare credentials in Worker secrets. Ensure CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID secrets are set.');
          return new Response('Internal Server Error - Configuration Missing', { status: 500 });
      }

      // 4. 构造发往 Cloudflare AI 的请求 (使用 Worker 的凭证)
      const aiApiUrl = `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/@cf/black-forest-labs/flux-1-schnell`;

      const aiRequest = new Request(aiApiUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiToken}`, // 使用 Worker 的 Token
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ prompt: prompt, steps: steps || 4 }), // 使用客户端的 Prompt
      });

      // 5. 发送请求到 AI API 并获取响应
      console.log(`Forwarding request to AI API for prompt: "${prompt}"`);
      const aiResponse = await fetch(aiRequest);
      console.log(`Received response from AI API with status: ${aiResponse.status}`);


      // 6. 将 AI 的响应直接返回给客户端
      // 创建一个新的 Response 对象以避免潜在的 header 问题或 immutability 问题
      const responseHeaders = new Headers(aiResponse.headers);
      //responseHeaders.set('X-Proxied-By', 'my-ai-proxy-worker'); // 添加一个自定义头（可选）

      return new Response(aiResponse.body, {
        status: aiResponse.status,
        statusText: aiResponse.statusText,
        headers: responseHeaders // 返回 AI 的响应头，可以按需修改
      });

    } catch (error: unknown) {
      console.error('Error processing request:', error);
      if (error instanceof SyntaxError) {
          return new Response('Invalid JSON in request body', { status: 400 });
      }
      // 避免将详细错误暴露给客户端
      return new Response(`Internal Server Error: ${error instanceof Error ? error.message : 'Unknown error'}`, { status: 500 });
    }
  },
} satisfies ExportedHandler<Env>; 